package com.chance.cc.crawler.development.scripts.sougou.searchKw;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Json;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.LabelTag;
import com.chance.cc.crawler.core.tags.crawler.CrawlerBusinessTags;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;
import static com.chance.cc.crawler.development.scripts.allfeild.AutoVMCommonField.Tag_Field_Topic_Type;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2021/4/19 16:29
 * @Description 搜狗问问  问题分类 搜索功能
 **/
public class SouGouSearchKwTagCrawlerScript extends CrawlerCommonScript {

    private static Logger log = LoggerFactory.getLogger(SouGouSearchKwTagCrawlerScript.class);
    private static final String DOMAIN = "sougou";
    private static final String SITE = "searchKwTag";
    private static final String REQUEST_AGAIN_TAG = DOMAIN + "_request_again";
    private static final String SEARCH_KW_SOURCE_URL = "searchKwSourceUrl";

    private static final String PREFIX = "https://wenwen.sogou.com";
    private static final String ENTRANCE_URL = "https://www.sogou.com/";
    private static final String SEARCH_URL = "https://wenwen.sogou.com/cate/tag\\S*";
    private static final String ITEM_URL = "http[s]*://wenwen.sogou.com/question/q\\d+.htm";
    private static final String COMMENT_URL = "http[s]*://wenwen.sogou.com/question/q\\d+.htm\\?pg=\\d+\\S*";
    private static final String COMMENT_REPLY_SOURCE_URL = "https://wenwen.sogou.com/wapi/ms/comments?ansid=%s&questionId=%s&start=0&len=100";
    private static final String COMMENT_REPLY_URL = "https://wenwen.sogou.com/wapi/ms/comments\\S*";


    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return DOMAIN;
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(ENTRANCE_URL);
        addUrlRegular(SEARCH_URL);
        addUrlRegular(ITEM_URL);
        addUrlRegular(COMMENT_URL);
        addUrlRegular(COMMENT_REPLY_URL);
    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        String siteTag = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        return siteTag.equals(SITE);
    }

    @Override
    public List<CrawlerRecord> prepareRequest(CrawlerRequestRecord requestRecord, List<CrawlerRequestRecord> supportSourceRecords) {
        List<CrawlerRecord> crawlerRecords = new ArrayList<>();
        for (CrawlerRequestRecord supportSourceRecord : supportSourceRecords) {
            String url = supportSourceRecord.getHttpRequest().getUrl();
            if (url.contains("keys")) {
                initKeyword(requestRecord, supportSourceRecord, crawlerRecords);
            }
        }

        requestRecord.getHttpRequest().addHeader("User-Agent",getRandomUA());
        return crawlerRecords;
    }

    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();
        String requestUrl = crawlerRequestRecord.getHttpRequest().getUrl();

        if (!httpPage.isDownloadSuccess() || httpPage.getStatusCode() != 200) {
            log.error("{} status code : [{}]",requestUrl,httpPage.getStatusCode());
            requestAgainCrawlerRecord(parsedLinks, crawlerRequestRecord);
            crawlerRequestRecord.setNeedWashPage(false);
            return parsedLinks;
        }

        if (requestUrl.matches(SEARCH_URL)) {
            searchUrlRecord(crawlerRequestRecord, httpPage, parsedLinks);
        }

        if (requestUrl.matches(ITEM_URL)) {
            itemUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        if(requestUrl.matches(COMMENT_URL)){
            commentUrlRecord(crawlerRequestRecord,httpPage,parsedLinks);
        }

        return parsedLinks;
    }

    private void searchUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        String keyword = (String) httpPage.getRequest().getExtras().get("keyword");
        //翻页
        String nextUrl = httpPage.getHtml().xpath("//a[@class=\"btn-page-next\"]/@href").get();
        if (StringUtils.isNotBlank(nextUrl)) {
            nextUrl = PREFIX + StringEscapeUtils.unescapeHtml(nextUrl);
            CrawlerRequestRecord nextRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(nextUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .copyResultTags()
                    .build();
            nextRecord.getHttpRequest().setExtras(httpPage.getRequest().getExtras());
            parsedLinks.add(nextRecord);
        }


        //列表解析
        List<Selectable> nodes = httpPage.getHtml().xpath("//ul[@class=\"sort-lst\"]/li").nodes();
        for (Selectable node : nodes) {
            String itemUrl = node.xpath("./a/@href").get();
            if (StringUtils.isBlank(itemUrl)) {
                continue;
            }
            itemUrl = PREFIX + itemUrl.split("\\?")[0];

            String releaseTime = node.xpath(".//div[@class=\"sort-rgt\"]//span[last()]/text()").get();
            if(StringUtils.isBlank(releaseTime)){
                continue;
            }

            try {
                long releaseTimeToLong = washTime(releaseTime);
                CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                        .itemPageRequest(crawlerRequestRecord)
                        .httpUrl(itemUrl)
                        .recordKey(itemUrl + keyword)
                        .releaseTime(releaseTimeToLong)
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                parsedLinks.add(itemRecord);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
    }

    private void itemUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks) {
        CrawlerResultTags resultTags = crawlerRequestRecord.tagsCreator().resultTags();
        if (resultTags.hasDataType(comment)) {
            resultTags.getCategoryTag().removeLabelTag("comment");

            CrawlerRequestRecord filterRecord = resultTags.getCategoryTag().getKVTagObjVal("comment_filter_record", CrawlerRequestRecord.class);
            if (filterRecord == null) {
                log.error("filter record can not null !");
                return;
            }

            //评论数要大于0 顺序排列
            String comments = washContent("\\d+条回答", httpPage.getRawText());
            comments = StringUtils.isNotBlank(comments) ? comments.split("条")[0].trim() : "0";
            if (Integer.parseInt(washNum(comments) )> 0) {
                String commentUrl = httpPage.getRequest().getUrl() + "?pg=0";
                CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .httpUrl(commentUrl)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .copyBizTags()
                        .needWashed(true)
                        .resultLabelTag(comment)
                        .build();
                commentRecord.setFilter(filterRecord.getFilter());
                commentRecord.setFilterInfos(filterRecord.getFilterInfos());
                commentRecord.getHttpRequest().addExtra("articleUrl",crawlerRequestRecord.getHttpRequest().getUrl());
                parsedLinks.add(commentRecord);
            }
        }
    }

    private void commentUrlRecord(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage, List<CrawlerRequestRecord> parsedLinks){
        String articleUrl = (String) crawlerRequestRecord.getHttpRequest().getExtras().get("articleUrl");
        String commentUrl = httpPage.getHtml().xpath("//a[@class=\"btn-page-next next_page\"]/@href").get();
        if(StringUtils.isNotBlank(commentUrl)){
            commentUrl = PREFIX + StringEscapeUtils.unescapeHtml(commentUrl);
            CrawlerRequestRecord commentRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(commentUrl)
                    .releaseTime(System.currentTimeMillis())
                    .copyBizTags()
                    .needWashed(true)
                    .copyResultTags()
                    .build();
            commentRecord.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
            parsedLinks.add(commentRecord);
        }

        //评论的回复
        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"replay-section answer_item\"]").nodes();
        for (Selectable node : nodes) {
            String commentId = node.xpath("./@data-id").get();
            String comments = node.xpath(".//a[@class=\"btn-comment get_comment\"]/@data-num").get();
            if(Integer.parseInt(comments) < 1){
                continue;
            }

            String id = articleUrl.substring(articleUrl.lastIndexOf("/") + 1, articleUrl.lastIndexOf("."));
            String url = String.format(COMMENT_REPLY_SOURCE_URL,commentId,id.substring(1));
            CrawlerRequestRecord record = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRequestRecord)
                    .httpUrl(url)
                    .releaseTime(System.currentTimeMillis())
                    .notFilterRecord()
                    .copyBizTags()
                    .needWashed(true)
                    .copyResultTags()
                    .build();
            record.getHttpRequest().setExtras(crawlerRequestRecord.getHttpRequest().getExtras());
            parsedLinks.add(record);
        }
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        String requestUrl = page.getRequest().getUrl();

        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(interaction)) {
            crawlerDataList.add(washInteraction(crawlerRecord, page));
        }

        if (crawlerResultTags.hasDataType(comment)) {
            if(requestUrl.matches(COMMENT_URL)){
                crawlerDataList.addAll(washComment(crawlerRecord, page));
            }

            if(requestUrl.matches(COMMENT_REPLY_URL)){
                crawlerDataList.addAll(washCommentReply(crawlerRecord,page));
            }
        }

        return crawlerDataList;
    }

    private CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1, itemUrl.lastIndexOf("."));

        String title = httpPage.getHtml().xpath("//span[@class=\"detail-tit\"]/text()").get();
        String author = httpPage.getHtml().xpath("//span[@id=\"question_author\"]/text()|//a[@class=\"user-name\"]/text()").get();
        String authorId = httpPage.getHtml().xpath("//div[@class=\"ft-info-box\"]//a[@class=\"user-name\"]/@href").get();
        authorId = StringUtils.isNotBlank(authorId) ? authorId.substring(authorId.lastIndexOf("uid") + 4,authorId.lastIndexOf("&")) : "";
        String releaseTime = httpPage.getHtml().xpath("//div[@class=\"user-txt\"]/span[last()]").get();
        List<String> all = httpPage.getHtml().xpath("//pre[@class=\"detail-tit-info\"]//text()").all();
        StringBuffer contentBf = new StringBuffer();
        for (String s : all) {
            contentBf.append(s).append(" ");
        }
        List<String> imgs = httpPage.getHtml().xpath("//div[@id=\"question_images\"]//img/@data-src").all();
        List<String> all1 = httpPage.getHtml().xpath("//div[@class=\"tags\"]/a/text()").all();


        CrawlerData crawlerData = null;
        try {
            long releaseTimeToLong = StringUtils.isNotBlank(releaseTime) && releaseTime.contains("提问") ? washTime(releaseTime.split("提问")[0].trim()) : crawlerRequestRecord.getReleaseTime();
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .addContentKV(Field_Title, title)
                    .addContentKV(Field_Author,author)
                    .addContentKV(Field_Author_Id,authorId)
                    .addContentKV(Field_Images, imgs.toString())
                    .addContentKV(Field_Content,contentBf.toString())
                    .build();
            if(all1 != null && all1.size() > 0){
                crawlerData.tagsCreator().bizTags().addCustomKV(Tag_Field_Topic_Type,all1);
            }
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return crawlerData;
    }

    private CrawlerData washInteraction(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1, itemUrl.lastIndexOf("."));

        String comments = washContent("\\d+条回答", httpPage.getRawText());
        comments = StringUtils.isNotBlank(comments) ? comments.split("条")[0].trim() : "0";
        String views = washContent("\\d+ 次浏览", httpPage.getRawText());
        views = StringUtils.isNotBlank(views) ? views.split("次")[0].trim() : "0";
        String releaseTime = httpPage.getHtml().xpath("//div[@class=\"user-txt\"]/span[last()]").get();


        CrawlerData  crawlerData = null;
        try {
            long releaseTimeToLong = StringUtils.isNotBlank(releaseTime) && releaseTime.contains("提问") ? washTime(releaseTime.split("提问")[0].trim()) : crawlerRequestRecord.getReleaseTime();
            crawlerData = CrawlerData.builder()
                    .data(crawlerRequestRecord, httpPage)
                    .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                    .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, interaction.enumVal(), articleKey))
                    .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                    .url(itemUrl)
                    .releaseTime(releaseTimeToLong)
                    .addContentKV(Field_I_Comments, washNum(comments))
                    .addContentKV(Field_I_Views, washNum(views))
                    .build();
        } catch (ParseException e) {
            log.error(e.getMessage());
        }

        return crawlerData;
    }

    public List<CrawlerData> washComment(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String articleUrl = (String) httpPage.getRequest().getExtras().get("articleUrl");
        String articleKey = articleUrl.substring(articleUrl.lastIndexOf("/") + 1, articleUrl.lastIndexOf("."));

        List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"replay-section answer_item\"]").nodes();
        for (Selectable node : nodes) {
            String commentId = node.xpath("./@data-id").get();
            String author = node.xpath(".//a[@class=\"user-name\"]/text()|.//span[@class=\"user-name\"]/text()").get();
            String authorId = node.xpath(".//a[@class=\"user-name\"]/@data-uid").get();
            String releaseTime = node.xpath(".//div[@class=\"user-txt\"]/text()").get();
            releaseTime = StringUtils.isBlank(releaseTime) ? node.xpath(".//div[@class=\"user-txt\"]/span[last()]/text()").get() : releaseTime;
            List<String> all = node.xpath(".//pre[@class=\"replay-info-txt answer_con\"]//text()").all();
            StringBuffer contentBf = new StringBuffer();
            for (String s : all) {
                contentBf.append(s).append(" ");
            }

            try {
                long releaseTimeToLong = StringUtils.isNotBlank(releaseTime) && releaseTime.contains("回答") ? washTime(releaseTime.split("回答")[0].trim()):crawlerRequestRecord.getReleaseTime();
                CrawlerData crawlerData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                        .releaseTime(releaseTimeToLong)
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_Author, author)
                        .addContentKV(Field_Author_Id, authorId)
                        .addContentKV(Field_Content, contentBf.toString())
                        .build();
                crawlerDataList.add(crawlerData);


                String comments = node.xpath(".//a[@class=\"btn-comment get_comment\"]/@data-num").get();
                String likes = node.xpath(".//a[@title=\"点赞\"]/@data-num").get();
                String disLikes = node.xpath(".//a[@title=\"呵呵\"]/@data-num").get();
                CrawlerData interactionData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), commentId))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(), CrawlerEnum.CrawlerDataType.interaction.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("interaction"))
                        .releaseTime(releaseTimeToLong)
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_I_Likes, likes)
                        .addContentKV(Field_I_Dislikes, disLikes)
                        .addContentKV(Field_I_Comments,comments)
                        .build();
                crawlerDataList.add(interactionData);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
        return crawlerDataList;
    }

    public List<CrawlerData> washCommentReply(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        String site = crawlerRequestRecord.tagsCreator().bizTags().getCategoryTag().getKVTagStrVal("site");
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        String requestUrl = httpPage.getRequest().getUrl();
        String articleUrl = (String) httpPage.getRequest().getExtras().get("articleUrl");
        String articleKey = articleUrl.substring(articleUrl.lastIndexOf("/") + 1, articleUrl.lastIndexOf("."));


        JSONArray jsonArray = JSONArray.parseArray(httpPage.getRawText());
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject) o;
            String commentId = jsonObject.getString("id");
            String author = jsonObject.getJSONObject("author").getString("name");
            String authorId = jsonObject.getString("authorId");
            String content = jsonObject.getString("content");
            String releaseTime = jsonObject.getString("createTimeStr");

            try {
                Long releaseTimeToLong = StringUtils.isNotBlank(releaseTime) ? washTime(releaseTime) : crawlerRequestRecord.getReleaseTime();
                CrawlerData crawlerData = CrawlerData.builder()
                        .data(crawlerRequestRecord, httpPage)
                        .parentId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                        .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), site, comment.enumVal(),comment.enumVal(), commentId))
                        .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("comment"))
                        .releaseTime(releaseTimeToLong)
                        .url(requestUrl)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.filter)
                        .requestLabelTag(CrawlerEnum.CrawlerRequestType.result)
                        .addContentKV(Field_Author, author)
                        .addContentKV(Field_Author_Id, authorId)
                        .addContentKV(Field_Content, content)
                        .build();
                crawlerDataList.add(crawlerData);
            } catch (ParseException e) {
                log.error(e.getMessage());
            }
        }
        return crawlerDataList;
    }

    private static String washContent(String regx, String input) {
        Pattern compile = Pattern.compile(regx);
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return null;
    }

    private static String washNum(String num){
        if(StringUtils.isBlank(num)){
            return "0";
        }

        if(num.contains("万")){
            String[] split = num.split("万");
            String numDoubule = String.valueOf(10000 * Double.parseDouble(split[0]));
            return numDoubule.split("\\.")[0];
        }

        return num;
    }

    private long washTime(String time) throws ParseException {
        if (StringUtils.isBlank(time)) {
            return 0;
        }

        long currentTimeMillis = System.currentTimeMillis();
        if ("刚刚".equals(time) || "今天".equals(time)) {
            return currentTimeMillis;
        }

        if (time.contains("秒前") || time.contains("秒之前")) {
            String[] split = time.split("秒");
            return currentTimeMillis - (DateUtils.MILLIS_PER_SECOND * (Integer.parseInt(split[0])));
        }

        if (time.contains("分钟前") || time.contains("分钟之前")) {
            String[] split = time.split("分钟");
            return currentTimeMillis - (DateUtils.MILLIS_PER_MINUTE * (Integer.parseInt(split[0])));
        }

        if (time.contains("小时前") || time.contains("小时之前")) {
            String[] split = time.split("小时");
            return currentTimeMillis - (DateUtils.MILLIS_PER_HOUR * (Integer.parseInt(split[0])));
        }

        if ("昨天".equals(time)) {
            return currentTimeMillis - DateUtils.MILLIS_PER_DAY;
        }

        if ("前天".equals(time)) {
            return currentTimeMillis - (DateUtils.MILLIS_PER_DAY * 2);
        }

        if (time.contains("天前") || time.contains("天之前")) {
            String[] split = time.split("天");
            return currentTimeMillis - (DateUtils.MILLIS_PER_DAY * (Integer.parseInt(split[0])));
        }

        if (time.contains("周前") || time.contains("周之前")) {
            String[] split = time.split("周");
            return currentTimeMillis - (DateUtils.MILLIS_PER_DAY * 7 * (Integer.parseInt(split[0])));
        }

        if (time.contains("月前") || time.contains("月之前")) {
            String[] split = time.split("月");
            return currentTimeMillis - (DateUtils.MILLIS_PER_DAY * 30 * (Integer.parseInt(split[0])));
        }

        if (time.contains("年前") || time.contains("年之前")) {
            String[] split = time.split("年");
            return currentTimeMillis - (DateUtils.MILLIS_PER_DAY * 365 * (Integer.parseInt(split[0])));
        }

        LocalDate now = LocalDate.now();
        if (time.matches("\\d{2}-\\d{2} \\d{2}:\\d{2}")) {
            time = now.getYear() + time;
        }
        return DateUtils.parseDate(time.trim(), "yyyyMM-dd HH:mm", "yyyy-MM-dd HH:mm", "yyyy-MM-dd","yyyy.MM.dd HH:mm").getTime();
    }


    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

    private void requestAgainCrawlerRecord(List<CrawlerRequestRecord> crawlerRequestRecords, CrawlerRequestRecord crawlerRecord) {
        CrawlerBusinessTags crawlerBusinessTags = crawlerRecord.tagsCreator().bizTags();
        int count = 0;
        if (crawlerBusinessTags.hasKVTag(REQUEST_AGAIN_TAG)) {
            count = (int) crawlerBusinessTags.getCategoryTag().getKVTag(REQUEST_AGAIN_TAG).getVal();
            if (count >= 5) {
                log.error(DOMAIN + " download page the number of retries exceeds the limit" +
                        ",request url {}", crawlerRecord.getHttpRequest().getUrl());
                return;
            }
        }

        String requestUrl = crawlerRecord.getHttpRequest().getUrl();
        LabelTag type = crawlerRecord.tagsCreator().requestTags().getCategoryTag().getLabelTags().get("turn_page_item_request");
        CrawlerRequestRecord crawlerRequestRecord = null;
        if (type == null) {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .turnPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .notFilterRecord()
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        } else {
            crawlerRequestRecord = CrawlerRequestRecord.builder()
                    .itemPageRequest(crawlerRecord)
                    .httpUrl(requestUrl)
                    .releaseTime(crawlerRecord.getReleaseTime())
                    .recordKey(crawlerRecord.getRecordKey() + count)
                    .copyBizTags()
                    .copyResultTags()
                    .build();
        }

        if (crawlerRequestRecord == null) {
            return;
        }

        crawlerRequestRecord.getHttpRequest().setExtras(crawlerRecord.getHttpRequest().getExtras());
        crawlerRequestRecord.getHttpRequest().setHeaders(crawlerRecord.getHttpRequest().getHeaders());
        crawlerRequestRecord.setNeedWashPage(crawlerRecord.isNeedWashPage());
        crawlerRequestRecord.setNeedParsedPage(crawlerRecord.isNeedParsedPage());
        crawlerRequestRecord.tagsCreator().bizTags().addCustomKV(REQUEST_AGAIN_TAG, ++count);
        crawlerRequestRecords.add(crawlerRequestRecord);
    }

    private void initKeyword(CrawlerRequestRecord requestRecord, CrawlerRequestRecord supportSourceRecord, List<CrawlerRecord> crawlerRecords) {
        HttpPage internalDownloadPage = supportSourceRecord.getInternalDownloadPage();
        Map<String, Object> extras = requestRecord.getHttpRequest().getExtras();
        String searchSourceUrl = (String) extras.get(SEARCH_KW_SOURCE_URL);
        if (StringUtils.isBlank(searchSourceUrl)) {
            log.error("search kw source url can not null!");
            return;
        }
        Json json = internalDownloadPage.getJson();
        String msg = json.jsonPath($_type + ".msg").get();
        if (!"success".equals(msg)) {
            log.error("keyword page [{}] download error!", internalDownloadPage.getRequest().getUrl());
            return;
        }

        List<String> all = json.jsonPath($_type + ".content").all();
        for (String data : all) {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String keyword = jsonObject.getString("keyword");

            try {
                String url = String.format(searchSourceUrl, URLEncoder.encode(keyword, "UTF-8"));
                CrawlerRequestRecord turnRecord = CrawlerRequestRecord.builder()
                        .turnPageRequest(requestRecord)
                        .httpUrl(url)
                        .releaseTime(System.currentTimeMillis())
                        .notFilterRecord()
                        .copyBizTags()
                        .copyResultTags()
                        .build();
                turnRecord.tagsCreator().bizTags().addKeywords(keyword);
                turnRecord.getHttpRequest().addExtra("keyword", keyword);
                crawlerRecords.add(turnRecord);
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
        }
    }

    private static List<String> agentList = new ArrayList<>();

    static {
        agentList.add("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 7.0; InfoPath.3; .NET CLR 3.1.40767; Trident/6.0; en-IN)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/4.0; InfoPath.2; SV1; .NET CLR 2.0.50727; WOW64)");
        agentList.add("Mozilla/5.0 (compatible; MSIE 10.0; Macintosh; Intel Mac OS X 10_7_3; Trident/6.0)");
        agentList.add("Mozilla/4.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/5.0)");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.2 (KHTML, like Gecko) ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/532.2");
        agentList.add("Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.28.3 (KHTML, like Gecko) Version/3.2.3 ChromePlus/4.0.222.3 Chrome/4.0.222.3 Safari/525.28.3");
        agentList.add("Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16");
        agentList.add("Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14");
        agentList.add("Mozilla/5.0 (Windows NT 6.0; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 12.14");
        agentList.add("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0) Opera 12.14");
        agentList.add("Opera/12.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.02");
        agentList.add("Opera/9.80 (Windows NT 6.1; U; es-ES) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/9.80 (Windows NT 5.1; U; zh-sg) Presto/2.9.181 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.2;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");
        agentList.add("Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        agentList.add("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0");
        agentList.add("Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.13 Safari/537.36");
        agentList.add("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4043.400");
    }

    private static String getRandomUA(){
        return agentList.get(RandomUtils.nextInt(0,agentList.size() - 1));
    }

    public static void main(String[] args) {
        StringBuffer s = new StringBuffer();
        System.out.println(s.toString());
    }
}
